package com.pengtu.service.asset;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.Constants;
import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.dao.asset.Message.NewsDao;
import com.pengtu.dao.asset.Message.PublishDao;
import com.pengtu.dao.asset.Message.RegulationsDao;
import com.pengtu.entity.app.Attachment;
import com.pengtu.entity.asset.Message.News;
import com.pengtu.entity.asset.Message.Publish;
import com.pengtu.entity.asset.Message.Regulations;
import com.pengtu.model.PublishModel;
import com.pengtu.utils.FileUtils;

@Component
@Transactional
public class MessageManager {

	private PublishDao publishDao;
	private RegulationsDao regulationsDao;
	private NewsDao newsDao;

	////    Publish 对象
	
	/**
	 * 添加
	 */
	public void saveOrupdatePublish(Publish publish){
		publishDao.save(publish);
	}
	/**
	 * 删除
	 * @param id 主键值
	 */
	public void deletePublish(String id){
		publishDao.delete(id);
	}
	/**
	 * 根据属性名和属性值查找单挑对象
	 * @param propertyName
	 * @param value
	 * @return
	 */
	@Transactional(readOnly=true)
	public Publish getPublish(String propertyName ,String value){
		if(propertyName.equalsIgnoreCase("id"))
			return publishDao.get(value);
		return publishDao.findUniqueBy(propertyName, value);
	}
	/**
	 * 模糊查询
	 * @param page
	 * @param queryFilter
	 * @return
	 */
	@Transactional(readOnly=true)
	public Page<Publish> findPagePublish(final Page<Publish> page,final QueryFilter queryFilter){
		return publishDao.findPage(page, queryFilter);
	}
	
	
	////News 对象
	/**
	 * 保存
	 */
	public void saveOrUpdateNews(News news){
		newsDao.save(news);
	}
	/**
	 * 根据主键删除
	 * @param id
	 */
	public void deleteNews(String id){
		newsDao.delete(id);
	}
	/**
	 * 根据属性查找单条对象
	 * @param propertyName
	 * @param value
	 * @return
	 */
	@Transactional(readOnly=true)
	public News getNews(String propertyName ,String value){
		if(propertyName.equalsIgnoreCase("id"))
			return newsDao.get(value);
		return newsDao.findUniqueBy(propertyName, value);
	}
	/**
	 * 模糊查询
	 * @param page
	 * @param filters
	 * @return
	 */
	@Transactional(readOnly=true)
	public Page<News> findNews(final Page<News> page,final QueryFilter filters){
		return newsDao.findPage(page, filters);
	}
	
	//// Regulations 对象
	/**
	 * 添加制度信息
	 */
	public void saveOrUpdateRegulation(Regulations regulation){
		regulationsDao.save(regulation);
	}
	/**
	 * 根据主键删除
	 * @param id
	 */
	public void deleteRegulations(String id){
		regulationsDao.delete(id);
	}
	/**
	 * 根据属性名查询单条记录
	 * @param propertyName
	 * @param value
	 * @return
	 */
	@Transactional(readOnly=true)
	public Regulations getRegulations(String propertyName,String value){
		if(propertyName.equalsIgnoreCase("id"))
			return regulationsDao.get(value);
		return regulationsDao.findUniqueBy(propertyName, value);
	}
	/**
	 * 模糊查询
	 * @param page
	 * @param queryFilter
	 * @return
	 */
	@Transactional(readOnly=true)
	public Page<Regulations> findPageRegulations(final Page<Regulations> page,final QueryFilter queryFilter){
		return regulationsDao.findPage(page, queryFilter);
	}
	
	@Autowired
	public void setPublishDao(PublishDao publishDao) {
		this.publishDao = publishDao;
	}
	@Autowired
	public void setRegulationsDao(RegulationsDao regulationsDao) {
		this.regulationsDao = regulationsDao;
	}
	@Autowired
	public void setNewsDao(NewsDao newsDao) {
		this.newsDao = newsDao;
	}
	public void updatePublishShow(String publishsId, String showTag) {
		// TODO Auto-generated method stub
		if(StringUtils.isNotEmpty(publishsId)){
			 publishsId = publishsId.substring(0, publishsId.lastIndexOf("_"));
			 String [] publishIdArray = publishsId.split("_");
			 for (int i = 0; i < publishIdArray.length; i++) {
				publishDao.findUniqueBy("id", publishIdArray[i]).setShowTags(showTag);
			}
		}
	}
	/**
	 * 获得上传文件
	 */
	@Deprecated
    public Attachment uploadFile(Attachment attachment,String tableName, String tableField) {
    	//获取web应用程序在服务器上的路径需要访问Servlet Api
		ServletContext scon = ServletActionContext.getServletContext();
		//取得web应用在服务器上的物理地址
		String absoluteSavePath = scon.getRealPath("/");
		File saveDirectory = new File(absoluteSavePath);
		//如果不存在，则创建
		if(!saveDirectory.exists())saveDirectory.mkdir();
		//保存的文件名
		String saveName = this.createSaveFileName(attachment.getUpfileFileName());
		//保存服务器端的文件名
		attachment.setPath(saveName);
		attachment.setTableName(tableName);
		attachment.setTableField(tableField);
		String fileFullPath = attachment.getSavePath()+Constants.FILE_SEP+tableName+Constants.FILE_SEP+saveName;
		attachment.setFullPath(fileFullPath);
		//保存文件
		saveFile(new File(absoluteSavePath+fileFullPath),attachment);
		return attachment;
	}

	/**
     * 保存到服务器上的文件名
     * @return
     */
	private String createSaveFileName(String upfileFileName) {
		// TODO Auto-generated method stub
		String extension =upfileFileName.substring(upfileFileName.lastIndexOf("."));
		return System.currentTimeMillis() +extension;
	}



	/**
	 * 保存文件
	 * @param file
	 */
    private void saveFile(File file,Attachment attachment) {
		// TODO Auto-generated method stub
		try {
			FileUtils.makeDirectory(file);
			FileOutputStream fileOutputStream= new FileOutputStream(file);
			BufferedOutputStream buffereOutStream = new BufferedOutputStream(fileOutputStream);
		
			FileInputStream fileInputStream = new FileInputStream(attachment.getUpfile());
			BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
			
			byte [] buffer = new byte[1024];
			int length = -1;
			try {
				while ((length=fileInputStream.read(buffer))!=-1) {
						buffereOutStream.write(buffer,0,length);
				}
				buffereOutStream.close();
				fileOutputStream.close();
				bufferedInputStream.close();
				fileInputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
    
	/**获取在首页显示的新闻列表*/
	public  List<News> getTopNews() {
		return newsDao.getTopNews();
	}
	
	public List<Publish> getTopNotice() {
		return publishDao.getTopNotice();
	}
	
	
	/**
	 * 
	 * createIndexByLucene:
	 * 适用:
	 * @param index存放索引路径
	 * @exception 
	 * @since  1.0.0
	 */
	public void createIndexByLucene(String index) {
		newsDao.createIndexByLucene(index);
		publishDao.createIndexByLucene(index);
	}
	
	
	/**
	 * 
	 * SearchByLucene:
	 * 适用:
	 * @param index索引查询的目录
	 * @param keyword关键词
	 * @param startDate开始时间  格式为 yyyyMMdd 例 20111120 
	 * @param endDate结束时间   格式为 yyyyMMdd 例 20111120 
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public List<News> SearchByLucene(String index,String keyword,String startDate, String endDate) {
		return newsDao.SearchByLucene(index,keyword,startDate,endDate);
	}
	
	public List<PublishModel> SearchPublishByLucene(String index,String keyword,String startDate, String endDate){
		return publishDao.SearchByLucene(index,keyword,startDate,endDate);
	}
}
